package com.hlbb.business;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hlbb.domain.bean.Address;
import com.hlbb.domain.bean.Camaster;
import com.hlbb.domain.bean.Customer;

@Service("accountManager")
@Transactional(value = "transactionManager", propagation = Propagation.REQUIRED)
public class AccountManager extends BaseManager {

	public void addCamaster(Camaster camaster) {
		
		getCamasterDAO().save(camaster);
		
	}
	
	
	public Customer getCustomerByLoginId(String loginId) throws Exception {

		List<Customer> customerList = getCustomerDAO().findByLoginId(loginId);
		return (customerList != null)? customerList.get(0): null;

	}
	
	public List<Customer> listCustomer() throws Exception {

		return getCustomerDAO().listCgsCustomer();

	}

	/**
	 * This method insert data into CUSTOMER table
	 */
	public void addCustomer(Customer customer) throws Exception {
		if (customer != null) {
			
			// MD5 password
			customer.setPassword(encodeString(customer.getPassword()));
			customer.setCreatedDate(new Date());
			customer.setUpdatedDate(new Date());
			// Call DAO layer to insert customer into database
			getCustomerDAO().addCustomer(customer);

			// Save address
			Address address = new Address();
			address.setAddressName("Address  !!!");
			address.setCreatedDate(new Date());
			address.setUpdatedDate(new Date());
			getAddressDAO().addAddress(address);
		}		
	}
	
	/**
	 * This method read customers from database and write into text file
	 */
	public void writeToFile(String fileName) throws Exception {
		
		// get customer list
		List<Customer> customerList = getCustomerDAO().listCgsCustomer();
		
		// write into file
		File outputfile = new File(fileName);
		if (outputfile.exists()) {
			outputfile.delete();
		}
		BufferedWriter writer = new BufferedWriter(new FileWriter(outputfile,true));

		Customer cust = null;
		if (customerList != null && customerList.size() > 0) {
			for (int i = 0; i < customerList.size(); i++) {
				cust = customerList.get(i);
				String strMessage =  cust.getCustomerId() + "|" + cust.getCustomerName() + "|" + cust.getLoginId();
	
				//wrire the statement run id
				writer.write(strMessage);
	
				//insert new line indicator
				writer.newLine();
			}
		}
		
		//close the writer
		writer.close();
	}
	
	public void listTest() throws Exception {
		getCustomerDAO().listTest();
	}
	
};